package com.teaching.teachingsupport.service.impl.administratorserviceimpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.teaching.teachingsupport.common.pojo.dataobject.*;
import com.teaching.teachingsupport.common.pojo.dto.request.CreateCourseRequest;
import com.teaching.teachingsupport.common.pojo.dto.response.TeacherDTO;
import com.teaching.teachingsupport.mapper.*;
import com.teaching.teachingsupport.mapper.TeacherMapper;
import com.teaching.teachingsupport.mapper.studentviewmapper.CourseMapper;
import com.teaching.teachingsupport.mapper.studentviewmapper.SemesterMapper;
import com.teaching.teachingsupport.mapper.teacherviewmapper.TeacherCourseMapper;
import com.teaching.teachingsupport.service.service2.Administratorservice.CourseManagementService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Slf4j
public class CourseManagementServiceImpl implements CourseManagementService {

    private final TeacherMapper teacherMapper;
    private final UserMapper userMapper;
    private final CourseMapper courseMapper;
    private final TeacherCourseMapper teacherCourseMapper;
    private final SemesterMapper semesterMapper;

    @Override
    public List<TeacherDTO> searchTeachers(String teacherNoOrName, String courseName, String status) {
        log.debug("开始搜索教师 - 工号/姓名: {}, 课程名称: {}, 状态: {}", 
                teacherNoOrName, courseName, status);

        // 1. 先从 user 表中获取符合条件的教师用户
        LambdaQueryWrapper<User> userWrapper = new LambdaQueryWrapper<User>()
            .eq(User::getRoleType, "教师");  // 只查找教师角色

        // 1.1 添加状态条件
        if (StringUtils.hasText(status)) {
            log.debug("添加用户状态过滤: {}", status);
            userWrapper.eq(User::getStatus, "正常".equals(status) ? 0 : 
                                          "锁定".equals(status) ? 1 : 
                                          "注销".equals(status) ? 2 : -1);
        }

        // 1.2 添加姓名搜索条件
        if (StringUtils.hasText(teacherNoOrName)) {
            userWrapper.like(User::getUsername, teacherNoOrName);
        }

        List<Long> teacherUserIds = userMapper.selectList(userWrapper)
            .stream()
            .map(User::getUserId)
            .collect(Collectors.toList());

        if (teacherUserIds.isEmpty() && StringUtils.hasText(teacherNoOrName)) {
            // 如果通过用户名没找到，尝试通过工号查找
            List<Teacher> teachersByNo = teacherMapper.selectList(
                new LambdaQueryWrapper<Teacher>()
                    .like(Teacher::getTeacherNo, teacherNoOrName)
            );
            
            if (!teachersByNo.isEmpty()) {
                teacherUserIds = teachersByNo.stream()
                    .map(Teacher::getUserId)
                    .collect(Collectors.toList());
                
                // 再次过滤状态
                if (StringUtils.hasText(status)) {
                    List<Long> finalTeacherUserIds = userMapper.selectList(
                        new LambdaQueryWrapper<User>()
                            .in(User::getUserId, teacherUserIds)
                            .eq(User::getStatus, "正常".equals(status) ? 0 : 
                                                "锁定".equals(status) ? 1 : 
                                                "注销".equals(status) ? 2 : -1)
                    ).stream()
                    .map(User::getUserId)
                    .collect(Collectors.toList());
                    
                    teacherUserIds = finalTeacherUserIds;
                }
            }
        }

        if (teacherUserIds.isEmpty()) {
            log.debug("没有找到匹配的教师");
            return new ArrayList<>();
        }

        // 2. 构建教师查询条件
        LambdaQueryWrapper<Teacher> teacherWrapper = new LambdaQueryWrapper<Teacher>()
            .in(Teacher::getUserId, teacherUserIds);

        // 3. 处理课程名称搜索
        if (StringUtils.hasText(courseName)) {
            log.debug("处理课程名称搜索: {}", courseName);
            
            // 3.1 查找匹配的课程
            List<Long> courseIds = courseMapper.selectList(
                new LambdaQueryWrapper<Course>()
                    .like(Course::getCourseName, courseName)
                    .select(Course::getCourseId)
            ).stream().map(Course::getCourseId).collect(Collectors.toList());

            if (!courseIds.isEmpty()) {
                log.debug("找到匹配课程数量: {}", courseIds.size());
                
                // 3.2 查找教授这些课程的教师
                List<Long> teacherIdsByCourse = teacherCourseMapper.selectList(
                    new LambdaQueryWrapper<TeacherCourse>()
                        .in(TeacherCourse::getCourseId, courseIds)
                        .select(TeacherCourse::getTeacherId)
                ).stream().map(TeacherCourse::getTeacherId).collect(Collectors.toList());

                if (!teacherIdsByCourse.isEmpty()) {
                    log.debug("找到教授这些课程的教师数量: {}", teacherIdsByCourse.size());
                    teacherWrapper.in(Teacher::getUserId, teacherIdsByCourse);
                } else {
                    log.debug("没有找到教授这些课程的教师");
                    return new ArrayList<>();
                }
            } else {
                log.debug("没有找到匹配的课程");
                return new ArrayList<>();
            }
        }

        // 4. 执行查询并转换结果
        List<Teacher> teachers = teacherMapper.selectList(teacherWrapper);
        log.debug("查询到的教师总数: {}", teachers.size());

        return teachers.stream()
            .map(this::convertToTeacherDTO)
            .collect(Collectors.toList());
    }

    @Override
    @Transactional
    public Boolean createCourse(CreateCourseRequest request) {
        try {
            // 创建课程
            Course course = new Course();
            course.setCourseName(request.getCourseName());
            course.setAcademicYear(request.getAcademicYear());
            // 设置其他必要字段
            courseMapper.insert(course);

            // 如果提供了班级ID，创建教师课程关联
            if (request.getClassIds() != null && !request.getClassIds().isEmpty()) {
                for (Long teacherId : request.getClassIds()) {
                    TeacherCourse teacherCourse = new TeacherCourse();
                    teacherCourse.setTeacherId(teacherId);
                    teacherCourse.setCourseId(course.getCourseId());
                    // 设置默认学期，实际应该从请求中获取
                    teacherCourse.setSemesterId(1L);
                    teacherCourseMapper.insert(teacherCourse);
                }
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    @Transactional
    public Boolean updateTeacher(Long teacherId, TeacherDTO request) {
        try {
            Teacher teacher = teacherMapper.selectById(teacherId);
            if (teacher == null) {
                return false;
            }

            teacher.setTitle(request.getTitle());
            teacher.setTeacherNo(request.getTeacherNo());
            teacher.setDepartment(request.getDepartment());
            teacherMapper.updateById(teacher);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    private TeacherDTO convertToTeacherDTO(Teacher teacher) {
        TeacherDTO dto = new TeacherDTO();
        BeanUtils.copyProperties(teacher, dto);
        // 获取用户名
        User user = userMapper.selectById(teacher.getUserId());
        if (user != null) {
            dto.setName(user.getUsername());
        }
        // 获取教授的课程
        List<String> courseNames = teacherCourseMapper.selectList(
            new LambdaQueryWrapper<TeacherCourse>()
                .eq(TeacherCourse::getTeacherId, teacher.getUserId())
        ).stream()
        .map(tc -> {
            Course course = courseMapper.selectById(tc.getCourseId());
            return course != null ? course.getCourseName() : null;
        })
        .filter(Objects::nonNull)
        .collect(Collectors.toList());
        
        dto.setCourseNames(courseNames);
        return dto;
    }
} 